import {
  GetSystemCpuUsed,
  GetSystemInfo,
  GetSystemMemUsed,
  GetSystemNetworkLoad
} from '@shared/types'
import { formatMemory } from '@shared/utils'
import nodeos from 'os'
import si from 'systeminformation'

export const getSystemInfo: GetSystemInfo = async () => {
  const os = await si.osInfo()
  const cpu = await si.cpu()
  const totalMem = nodeos.totalmem() // 单位为字节

  return {
    hostname: os.hostname,
    arch: os.arch,
    platform: os.platform,
    cpu: `${cpu.manufacturer} ${cpu.brand} ${cpu.speed}GHz`,
    totalMem: `${formatMemory(totalMem, 'GB')} GB`
  }
}

export const getSystemCpuUsed: GetSystemCpuUsed = async () => {
  const load = await si.currentLoad()
  return load.currentLoad
}

export const getSystemMemUsed: GetSystemMemUsed = async () => {
  const totalMem = nodeos.totalmem() // 总内存，单位字节
  const freeMem = nodeos.freemem() // 空闲内存，单位字节
  const usedMem = totalMem - freeMem // 已用内存，单位字节
  return {
    used: usedMem,
    total: totalMem,
    usedPercent: (usedMem / totalMem) * 100
  }
}

export const getSystemNetworkLoad: GetSystemNetworkLoad = async () => {
  const net = await si.networkStats()

  // 检查是否有网络接口数据
  if (!net || net.length === 0) {
    return {
      rx: 0, // 接收的字节数
      tx: 0 // 发送的字节数
    }
  }

  // 接收的字节数
  const rx = net[0].rx_bytes
  // 发送的字节数
  const tx = net[0].tx_bytes

  return {
    rx, // 接收的字节数
    tx // 发送的字节数
  }
}
